<template>
  <el-select
    v-model="selectedValue"
    :placeholder="placeholder"
    :disabled="disabled || warehouses.length === 0"
    :clearable="clearable"
    @change="handleChange"
  >
    <el-option v-if="showAllOption" label="全部" value="" />
    <el-option
      v-for="warehouse in warehouses"
      :key="warehouse.warehouseCode"
      :label="warehouse.warehouseName || '未知仓库'"
      :value="String(warehouse.warehouseCode) || ''"
    />
  </el-select>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { getWarehouseList } from '../api/warehouse'
import { ElMessage } from 'element-plus'

// 定义props
const props = defineProps({
  modelValue: {
    type: [Number, String],
    default: ''
  },
  placeholder: {
    type: String,
    default: '请选择仓库'
  },
  disabled: {
    type: Boolean,
    default: false
  },
  clearable: {
    type: Boolean,
    default: true
  },
  showAllOption: {
    type: Boolean,
    default: true
  }
})

// 定义emits
const emit = defineEmits(['update:modelValue', 'change'])

// 内部状态
const selectedValue = ref(props.modelValue)
const warehouses = ref([])
const loading = ref(false)

// 监听外部值的变化
watch(
  () => props.modelValue,
  (newValue) => {
    selectedValue.value = newValue
  }
)

// 监听内部值的变化
watch(
  selectedValue,
  (newValue) => {
    emit('update:modelValue', newValue)
  }
)

// 处理选择变化
const handleChange = (value) => {
  emit('change', value)
}

// 加载仓库数据
const loadWarehouses = async () => {
  if (loading.value) return

  loading.value = true
  try {
    // 使用apiRequest调用
    console.log('开始调用API获取仓库数据...')
    const response = await getWarehouseList()
    console.log('API调用返回:', response)

    // 处理数据
    const rawData = response?.$values || []
    console.log('原始仓库数据数量:', rawData.length)

    // 过滤有效仓库数据并处理字段
    const validWarehouses = rawData
      .filter(item => item && item.warehouseCode && item.warehouseName)
      .map(item => ({
        warehouseCode: String(item.warehouseCode).trim(),
        warehouseName: String(item.warehouseName).trim()
      }))
    console.log('有效仓库数据数量:', validWarehouses.length)

    // 添加全部选项到最前面
    if (props.showAllOption) {
      warehouses.value = [{ warehouseCode: '', warehouseName: '全部' }, ...validWarehouses]
    } else {
      warehouses.value = validWarehouses
    }
    console.log('最终仓库数据数量:', warehouses.value.length)

    if (validWarehouses.length === 0) {
      ElMessage.warning('未获取到有效的仓库数据')
    }
  } catch (error) {
    ElMessage.error('获取仓库列表失败: ' + error.message)
    console.error('Failed to load warehouses:', error)
    // 错误情况下，确保warehouses不为空数组，避免组件永久禁用
    warehouses.value = props.showAllOption ? [{ warehouseCode: '', warehouseName: '全部' }] : []
  } finally {
    loading.value = false
  }
}

// 组件挂载时加载数据
onMounted(() => {
  loadWarehouses()
})
</script>

<style scoped>
/* 可以添加组件特定样式 */
</style>